import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/api/user.dart';
import 'package:flutter_enjoy_plus/utils/EventBus.dart';
import 'package:flutter_enjoy_plus/utils/TokenManager.dart';

class MinePage extends StatefulWidget {
  const MinePage(
      {super.key, required this.activeIndex, required this.changeIndex});
  final int activeIndex;
  final Function(int) changeIndex;

  @override
  State<MinePage> createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> {
  Map userInfo = {'id': '', 'avatar': '', 'nickName': ''};

  // 菜单数据
  final List menuList = [
    {
      "title": "我的房屋",
      "icon": "assets/images/house_profile_icon@2x.png",
    },
    {
      "title": "我的报修",
      "icon": "assets/images/repair_profile_icon@2x.png",
    },
    {
      "title": "访客记录",
      "icon": "assets/images/visitor_profile_icon@2x.png",
    }
  ];

  // 退出登录
  _logout() {
    // 确认弹层
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
              title: const Text('提示'),
              content: const Text('确定要退出登录吗？'),
              actions: [
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: const Text('取消'),
                ),
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                    // 清除token
                    tokenManager.deleteToken();
                    // 清除用户信息
                    setState(() {
                      userInfo = {'id': '', 'avatar': '', 'nickName': ''};
                    });
                    // 跳转到首页
                    // 方式1：由于是一个页面，无法通过Navigator.pushNamed跳转，只能使用Navigator.pushReplacementNamed
                    // Navigator.pushReplacementNamed(context, '/');
                    // 方式2：利用父组件传递过来的下标参数，将tabs的下标设置为0
                    widget.changeIndex(0);
                  },
                  child: const Text('确定'),
                )
              ]);
        });
  }

  List<Widget> getTitleChild() {
    return [
      ClipRRect(
        borderRadius: BorderRadius.circular(50.0),
        child: userInfo['avatar'] != null && userInfo['avatar'] != ''
            ? Image.network(
                userInfo['avatar'],
                width: 50,
                height: 50,
              )
            : Image.asset(
                'assets/images/avatar_1.jpg',
                width: 50,
                height: 50,
              ),
      ),
      const SizedBox(width: 10),
      Text(userInfo['nickName'] ?? '用户名',
          style: const TextStyle(fontSize: 16, color: Colors.white)),
      const Spacer(),
      GestureDetector(
        onTap: () {
          Navigator.pushNamed(context, '/profile');
        },
        child: Row(
          children: [
            GestureDetector(
              onTap: () {
                Navigator.pushNamed(context, "/profile", arguments: userInfo);
              },
              child: const Text(
                '去完善信息',
                style: TextStyle(color: Colors.white),
              ),
            ),
            const Icon(
              Icons.arrow_forward_ios,
              color: Colors.white,
              size: 13,
            )
          ],
        ),
      )
    ];
  }

  List<Widget> getChildren() {
    return menuList
        .map(
          (item) => SizedBox(
              height: 50,
              child: GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  if (item['title'] == '我的房屋') {
                    Navigator.pushNamed(context, '/house');
                  }
                },
                child: Row(
                  children: [
                    Row(
                      children: [
                        Image.asset(
                          item['icon'],
                          width: 20,
                          height: 20,
                        ),
                        const SizedBox(
                          width: 10,
                        ),
                        Text(
                          item['title'],
                          style: const TextStyle(fontSize: 16),
                        )
                      ],
                    ),
                    const Spacer(),
                    const Icon(
                      Icons.arrow_forward_ios,
                      size: 12,
                      color: Colors.grey,
                    )
                  ],
                ),
              )),
        )
        .toList();
  }

  /* 
  didChangeDependencies: 如果依赖的数据发生了变化，如某些主题、路由参数，则会调用此方法。
  关注的是外部

  didUpdateWidget: 当父组件构建不同的Widget，则调用此方法。
  关注的是内部
  
   */

  @override
  void didUpdateWidget(covariant MinePage oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.activeIndex == 1) {
      getUserInfo();
    }
  }

  @override
  void initState() {
    super.initState();
    registerLoginEvent();
  }

  registerLoginEvent() {
    // 监听登录成功事件
    eventBus.on<loginEvent>().listen((event) {
      getUserInfo();
    });
  }

  void getUserInfo() async {
    userInfo = await getUserInfoAPI();
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color.fromARGB(200, 85, 145, 175),
      appBar: AppBar(
        title: const Text(
          '我的',
          style: TextStyle(color: Colors.white),
        ),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: ListView(
        children: [
          // 个人信息
          Container(
            padding: const EdgeInsets.all(10),
            child: GestureDetector(
              onTap: () {
                // Navigator.pushNamed(context, '/profile');
              },
              child: Row(
                children: getTitleChild(),
              ),
            ),
          ),
          Container(
            padding: const EdgeInsets.all(15),
            margin: const EdgeInsets.symmetric(vertical: 20, horizontal: 10),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10),
            ),
            child: Column(
              children: getChildren(),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(
              left: 10,
              right: 10,
            ),
            child: Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color.fromARGB(255, 204, 102, 102),
                      minimumSize: const Size(100, 50),
                    ),
                    onPressed: () {
                      _logout();
                    },
                    child: const Text(
                      '退出',
                      style: TextStyle(
                        color: Colors.white,
                      ),
                    ),
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }
}
